<template>
  <div class="eco">
    <div class="search">
      <div class="search-ttile">区间</div>

      <el-select @change="changeSelect" v-model="searchData.searchDate" placeholder="请选择">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        >
        </el-option>
      </el-select>
      <div class="search-ttile">时间</div>
      <el-date-picker
          v-model="searchData.searchDate1"
          style="margin-left: 20px"
          type="daterange"
          range-separator="~"
          :default-time="['00:00:00', '23:59:59']"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          v-if="datePickerType =='daterange'"
      />
      <el-date-picker
          v-model="searchData.searchDate1"
          style="margin-left: 20px"
          type="year"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          v-if="datePickerType =='year'"
      />
      <el-date-picker
          v-model="searchData.searchDate1"
          style="margin-left: 20px"
          type="monthrange"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          v-if="datePickerType =='month'"
      />
      <div class="search-button">
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button type="info" @click="handleExport">导出</el-button>
      </div>
    </div>
    <div class="table" v-if="tableData && tableData.length>0">
      <el-table
          class="bueatyScroll"
          :data="tableData"
          style="width: 100%;margin-bottom: 20px;"
          row-key="value"
          border
          default-expand-all
          max-height="800"
          id="exportTab"
          show-summary
          ref="eltable"
          :summary-method="getSummaries"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <!--        <el-table-column prop="index1" label="序号" width="250">-->
        <!--          <template slot-scope="scope">-->
        <!--            &lt;!&ndash;            <span>{{ scope.row.index1 }} {{ scope.row.label }}</span>&ndash;&gt;-->
        <!--            <span>{{ String(scope.row.index1) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column
            label="名称"
            prop="label"
            width="400"
            fixed
        >
          <template slot-scope="scope">
            <span>{{ scope.row.index1 }} {{ scope.row.label }}</span>
            <!--            <span>{{ scope.row.label }}</span>-->
          </template>
        </el-table-column>
        <el-table-column
            :label="i.name"
            :width="i.width"
            v-for="(i,index) in columnData"
            :key="index"
        >
          <template slot-scope="scope" v-if="scope.row.datalist.datapoints">
            <span v-if="scope.row.datalist.datapoints[index]&&scope.row.datalist.datapoints[index].length>0">
              {{ scope.row.datalist.datapoints[index][0] || 0 }}
            </span>
            <span v-else>0</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import {exportExcel} from "@/utils/excelConfig";

import {login} from "@/api";
import {setCookieToken} from "@/utils/auth";
import {mapActions, mapMutations} from "vuex";
import FileSaver from "file-saver";
import XLSX from "xlsx";
import {endDate, endMonthDate, endYearDate, startDate, startYearDate} from "@/utils/time";
import {getNeworganizations, getSimplejsonQuery} from "@/api/eco";
import {formatTime1, indexData, toTree} from "@/utils";

export default {
  name: "ecoWatch",
  async mounted() {
    this.SET_TOKEN('')
    let username = 'admin@advantech.com'
    let password = window.btoa('8IrXJ3XPr4dMgnQQ')
    const res = await login({username, password})
    setCookieToken(res.accessToken)
    this.SET_TOKEN(res.accessToken)

    this.searchData.searchDate1 = [startDate(), endDate()];
    await this.getList()


    setInterval(async () => {
      let username = 'admin@advantech.com'
      let password = window.btoa('8IrXJ3XPr4dMgnQQ')
      const res = await login({username, password})
      setCookieToken(res.accessToken)
      await this.SET_TOKEN(res.accessToken)
      console.log('res=>', res)
    }, 1000 * 60 * 30)
  },
  data() {
    return {
      options: [{
        value: 'year',
        label: '年'
      }, {
        value: 'month',
        label: '月'
      }, {
        value: 'day',
        label: '日'
      }],
      searchData: {
        searchDate: 'day',
        searchDate1: []
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      columnData: [
        {prop: "label", width: 300, name: "日期"}
      ],
      tableData: [],
      menuList: {},
      tableColumn: [],
      datePickerType: "daterange"
    }
  },
  methods: {
    ...mapActions(['setSize']),
    ...mapMutations(['SET_TOKEN']),
    search() {
      this.getList()
    },
    //改变年月日
    changeSelect(e) {
      if (e == 'year') {
        this.datePickerType = 'year'
        this.searchData.searchDate1 = [];
      }
      if (e == 'month') {
        this.datePickerType = 'month'
        this.searchData.searchDate1 = [];
      }
      if (e == 'day') {
        this.searchData.searchDate1 = [startDate(), endDate()];
        this.datePickerType = 'daterange'
      }
      console.log('this.datae=>', this.datePickerType)
    },
    async getList() {
      console.log('this.ser=>', this.searchData)
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      const res1 = await getNeworganizations() // 菜单数据
      this.menuList = res1[2]
      let arrList = this.treeToArray(res1[2].children)//数组拍平
      const paramsV1 = this.paramsData(arrList) // 重组查询数据
      const res2 = await getSimplejsonQuery(paramsV1) // 查询图表数据
      let columnList = []
      res2[0].datapoints.map((v, index) => {
        const obj = {
          name: formatTime1(v[1] * 1000, this.datePickerType),
          prop: 'datapoints',
          width: 150,
          index: index
        }
        columnList.push(obj)
      })
      this.columnData = columnList

      arrList.map(v1 => {
        res2.map(v2 => {
          if (v1.value == v2.nodeId) {
            v1.datalist = v2
          }
        })
      })
      var tabArr = toTree(arrList, '3976')

      tabArr = indexData(tabArr)
      // console.log('tabArr=>', tabArr)
      this.tableData = tabArr
      console.log('Json=>', JSON.stringify(this.tableData))
      loading.close();
    },
    download() {
      exportExcel('能管数据', this.exc_data);
    },
    listToTree(cityList) {
      let array = []
      cityList.forEach(item => { // 遍历对象数组
        item.children = cityList.filter(info => info.parentId === item.value) // 找到每个对象的子节点
        if (item.parentId === 0) {
          array.push(item) // 将一层节点放入新数组中
        }
      })
      return array //循环结束，返回结果
    },

    //数组拍平
    treeToArray(tree) {
      return tree.reduce((res, item) => {
        const {children, ...i} = item
        return res.concat(i, children && children.length ? this.treeToArray(children) : [])
      }, [])
    },

    paramsData(arr = []) {
      const body = {
        "tzoffset": 0,
        "timezone": 8,
        "mock": 0,
        "range": {
          "from": "",
          "to": "",
          "raw": {"from": "now-5m", "to": "now"}
        },
        "maxDataPoints": 5,
        "interval": "2.5s",
        "intervalMs": 2500,
        "targets": []
      }
      if (this.datePickerType == 'year') {
        body.range.from = startYearDate(this.searchData.searchDate1)
        body.range.to = endYearDate(this.searchData.searchDate1)
      }
      if (this.datePickerType == 'daterange') {
        body.range.from = this.searchData.searchDate1[0].toISOString()
        body.range.to = this.searchData.searchDate1[1].toISOString()
      }
      if (this.datePickerType == 'month') {
        body.range.from = this.searchData.searchDate1[0].toISOString()
        body.range.to = endMonthDate(this.searchData.searchDate1[1])
      }
      arr.map(v => {
        const obj = {
          "target": `${v.label}|172`,
          "queryType": "bems_multi",
          "building": "海辰电能",
          "apmOrgId": 1,
          "resourceId": v.value,
          "subitemCode": "01000",
          "formulaUnit": this.searchData.searchDate,
          "formulaType": 172,
          "param1": {"type": 1, "name": "换算方式", "key": "标煤/标電/標碳", "value": -1},
          "param2": {"type": 2, "name": "折算方式", "key": "總量/面積/人均", "value": 0},
          "nodeType": ""
        }
        body.targets.push(obj)
      })
      return body
    },
    //导出
    handleExport() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      try {
        const $e = this.$refs['eltable'].$el
        let $table = $e.querySelector('.el-table__fixed')
        if (!$table) {
          $table = $e
        }
        const wb = XLSX.utils.table_to_book($table, {raw: false})
        let wbout1 = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'})
        FileSaver.saveAs(
            new Blob([wbout1], {type: 'application/octet-stream'}),
            `能管.xlsx`,
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.error(e)
      }
      loading.close()
      // return wbout1;
    },
    getDate(time) {
      if (time) {
        let val = new Date(time);
        let Y = val.getFullYear();
        let M = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1);
        let D = val.getDate() < 10 ? '0' + val.getDate() : val.getDate();
        return Y + '-' + M + '-' + D;
      }
      return ''
    },
    getSum(tree, idx, sums, index) {
      if (tree && tree.length > 0) {
        tree.map(item => {
          sums[index] += Number(item[idx].datapoints[index - 1][0])
        })
      }
    },
    getSummaries(param) {
      console.log('param=>', param)
      const {columns, data} = param

      let sums = []
      // columns = columns
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        // 初始化合计行
        sums[index] = 0

        // 递归求和
        this.getSum(data, 'datalist', sums, index)
        // 如果求和得到的结果是非数字,则显示--
        if (isNaN(sums[index])) {
          sums[index] = '--'
        }
      })
      sums = sums.map(v => Number(v).toFixed(2))
      sums[0] = '合计'
      console.log('sum=>', sums)
      return sums
    }
  },
}
;
</script>
<style lang="scss" scoped>
#app {
  background-color: #eceeef;
}

.eco {
  padding: 30px;
}

.search {
  display: flex;
  background-color: #fff;

  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 10px;

  .search-ttile {
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    margin: 0 10px;
  }

  .search-button {
    margin-left: 20px;
  }
}

.table {
  margin-top: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

::v-deep {
  .el-table {
    border-radius: 5px;
  }

  .el-table__body-wrapper::-webkit-scrollbar-track-piece {
    background-color: #f8f8f8;
  }

  .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px;
  }

  .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #dddddd;
    border-radius: 100px;
  }

  .el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
    background-color: #bbb;
  }
}

/*
*改变浏览器默认的滚动条样式
*/

</style>
